﻿using System.Globalization;
using System.Web;
using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using NPOI.SS.UserModel;
using System;
using System.Data;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ultimus.WFServer;
using System.Linq;
using H2.NET.TaskRob;
using System.Configuration;
using H2.NET.DBUtility;

namespace H2.NET.Web.Pages.SMD
{
    public partial class NewReceiveDeposit : BasePage
    {
        private t_smd_Device _storeDevice;
        public int Storeid = 0;
        public bool _hasDevice;
        public string SeachStoreId = "";
        public DataTable RencovationType = null;
        public DataTable DeliveryType = null;
        public bool NeedDevice;
        public bool NeedRenovation;
        public bool isTransfer;
        protected void Page_Load(object sender, EventArgs e)
        {
            Storeid = TaskAPI.GetStoreId("storeid");
            btn_submit.Visible = TaskAPI.IsAllowSubmit;
            CKD_list.Visible = false;

            #region 确认发机选设备和美萍号
            var action = AksRequest.GetFormString("action");
            var deviceStoreID = AksRequest.GetFormInt("storeid");
            var keywords = AksRequest.GetFormString("keywords");
            var result = "";

            switch (action)
            {
                case "chooseDevice":
                    {
                        var devices = (t_smd_Device._StoreID == deviceStoreID & t_smd_Device._Status == Cache["Device_YX"]
                                                       & (t_smd_Device._DispenserModel.Like("%" + keywords + "%") | t_smd_Device._PcModel.Like("%" + keywords + "%") |
                                                          t_smd_Device._ShakerModel.Like("%" + keywords + "%")) & t_smd_Device._Status == Cache["Device_YX"]).List<t_smd_Device>(Storage.Context3);
                        foreach (var device in devices)
                        {
                            var info = "";
                            info += device.DeviceID + ",";
                            info += device.FullSetSN + ",";
                            info += device.MeiPinNo + ",";
                            info += device.DispenserModel + ",";
                            info += device.ShakerModel + ",";
                            info += device.PcModel + ",";
                            result += info + "|";
                        }
                        SuccessMsg(result);
                        return;
                    }
                case "CKD":
                    try
                    {
                        var ckdProcess = AksRequest.GetFormString("process");
                        var ckdIncident = AksRequest.GetFormString("incident");
                        DeliveryOrder(StoreService.GetSmdStoreById(AksRequest.GetFormInt("storeId")), null, false);

                        var ships = (t_smd_ShipOrderNumber._Process == ckdProcess &
                                                              t_smd_ShipOrderNumber._Incident == ckdIncident).List<t_smd_ShipOrderNumber>(Storage.Context3);
                        result = ships.Aggregate(result, (current, ship) => current + (ship.Mode + "|" + ship.Name + "*"));
                        SuccessMsg(result);
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                        return;
                    }
                    catch (Exception ex)
                    {
                        Logging.GetLogger().Error("调用NewReceiveDeposit.aspx方法'ajax生成出库单'出错：" + ex);
                    }
                    return;
                default:
                    if (AksRequest.GetQueryString("action") == "downCKD")
                    {
                        var fileName = AksRequest.GetQueryString("FileName");
                        var filePath = Util.AppSettings("path") + @"\" + "CKD" + @"\" + fileName;
                        var fs = new FileStream(filePath, FileMode.Open);
                        var bytes = new byte[(int)fs.Length];
                        fs.Read(bytes, 0, bytes.Length);
                        fs.Close();
                        Response.ContentType = "application/octet-stream";
                        //通知浏览器下载文件而不是打开
                        Response.ContentEncoding = System.Text.Encoding.UTF8;
                        Response.AddHeader("Content-Disposition", "attachment;  filename=" + Server.UrlEncode(fileName));
                        Response.BinaryWrite(bytes);
                        Response.Flush();
                        Response.End();
                    }
                    break;
            }
            #endregion

            #region 判断是否有设备带入
            var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
            if (Utils.StrToInt(TaskAPI.GetVariableBySingleValue("IsDevice"), 0) > 0)
            {
                _hasDevice = true;
            }
            #endregion

            if (TaskAPI.GetVariableBySingleValue("IsRenovation") == "1")
            {
                NeedRenovation = true;
            }
            if (TaskAPI.GetVariableBySingleValue("IsDevice") == "1" && TaskAPI.GetVariableBySingleValue("DeviceTransfer") != "1")
            {
                NeedDevice = true;
            }
            if (!Page.IsPostBack)
            {
                if (ReadOnly()) return;

                if (IsOverFlow)
                {
                    btn_submit.Visible = false;
                    JsTip(string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser));
                    return;
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");
                var cancel = TaskAPI.GetVariableBySingleValue("IsCancel");
                DwzAssessment1.NotNeedShow = (cancel != "1");
                isTransfer = (cancel == "1");
                #region Submit Document
                if (TaskAPI.Step == "Submit Document" || TaskAPI.Step == "Submit Margin Document")
                {

                    SetDepositType();

                    var financeConfirmed = TaskAPI.GetVariableBySingleValue("FinanceConfirmed");
                    assessment.Visible = !string.IsNullOrEmpty(financeConfirmed);

                    string blankVlue = TaskAPI.GetVariableBySingleValue("BlankVlue");
                    InitDeviceModes();

                    tb_Inform_Device.Visible = false;
                    tb_Delivery_Device.Visible = false;
                    tr_address.Visible = false;
                    DispenseModel.Visible = false;
                    PcModel.Visible = false;
                    ShakerModel.Visible = false;

                    //根据保证金类型并显示
                    //SetDepositType();
                    // 流程变量是否已在，如果有，则不能修改
                    uc_store1.IsCanEditAuthID = string.IsNullOrEmpty(blankVlue);
                    uc_store1.store = StoreService.GetSmdStoreById(Storeid);

                    if (storeMasterData != null)
                    {
                        l_DispenseModel.Text = storeMasterData.DispenseModel;
                        l_ShakerModel.Text = storeMasterData.ShakerModel;
                        l_PcModel.Text = storeMasterData.PcModel;


                        if (TaskAPI.GetVariableBySingleValue("FinanceConfirmed") != "")
                        {
                            tb_EapproveSN.Text = storeMasterData.EapproveSN;
                            tb_sb_postingDate.Text = storeMasterData.Channel;
                            tb_sb_payer.Text = storeMasterData.Telephone;
                            l_EapproveSN.Visible = false;
                            l_sb_payer.Visible = false;
                            l_sb_postingDate.Visible = false;
                        }

                        #region 如果是新开门店的话并且有设备
                        if (_hasDevice)
                        {
                            var deviceAmount = TaskAPI.GetVariableBySingleValue("Deposit");
                            tb_sb_Amount.Text = deviceAmount;
                            var eapproveSn = TaskAPI.GetVariableBySingleValue("SerialNumber");
                            tb_EapproveSN.Text = eapproveSn;
                            tb_BuyMachineDeposit.Text = storeMasterData.BuyMachineDeposit.HasValue ? storeMasterData.BuyMachineDeposit.Value.ToString("N") : "0";
                            tb_BuyMachineDeposit.Visible = false;
                            l_BuyMachineDeposit.Text = tb_BuyMachineDeposit.Text;
                            tb_sb_Amount.Visible = false;
                            l_sb_Amount.Text = Utils.StrToDecimal(deviceAmount, 0).ToString("N");
                        }
                        #endregion
                    }
                    Agreement.Style.Add("display", "none");

                    if (TaskAPI.Step == "Submit Margin Document") { tb_fj.Visible = true; }
                }
                #endregion

                #region 审批环节
                else
                {
                    //if (TaskAPI.GetVariableBySingleValue("IsRenovation") == "0")
                    //{
                    //    Agreement.Style.Add("display", "none");
                    //}

                    if (storeMasterData == null || Storeid == 0)
                    {
                        btn_submit.Visible = false;
                        ScriptManager.RegisterStartupScript(this, GetType(), "info_tip", "$.jBox.tip('加载数据失败，请关闭页面重新打开！', 'info');", true);
                        return;
                    }

                    // ReSharper disable once PossibleInvalidOperationException
                    uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");
                    assessment.Visible = true;

                    #region 加载门店数据并显示
                    // 门店数据
                    var store = (t_smd_Store._StoreID == Storeid).ListFirst<t_smd_Store>(Storage.Context3);
                    uc_store1.store = store;
                    uc_store1.Visible = true;
                    uc_store1.IsCanEditAuthID = false;
                    #endregion
                    hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                    hl_ExportPdf.Visible = true;
                    #region 审批项初始化
                    if (TaskAPI.Step == "Finance Confirm" || TaskAPI.Step == "Finance Margin Confirm")
                    {
                        tb_Inform_Device.Visible = false;
                        tb_Delivery_Device.Visible = false;
                        InitDeviceModes();
                        //tb_sb_Amount.Visible = false;
                        tb_sb_postingDate.Visible = false;
                        tb_sb_payer.Visible = false;
                        tr_address.Visible = false;

                        Agreement.Visible = false;//隐藏履约保证金
                        ajaxUpload1.AllowUpload = false;
                        ajaxUpload1.AllowDelete = false;

                        if (_hasDevice && (TaskAPI.GetVariableBySingleValue("DeviceTransfer") != "1"))
                        {
                            DispenseModel.SelectedValue = storeMasterData.DispenseModel;
                            ShakerModel.SelectedValue = storeMasterData.ShakerModel;
                            Logging.GetLogger().Debug(ShakerModel.SelectedValue);
                            Logging.GetLogger().Debug("kaishi");
                            Logging.GetLogger().Debug(storeMasterData.PcModel);
                            PcModel.SelectedValue = storeMasterData.PcModel;
                            Logging.GetLogger().Debug(PcModel.SelectedValue);

                        }
                        ShowNeedForm();

                        //tb_fj.Visible = true;//显示上传底单

                        if (TaskAPI.GetVariableBySingleValue("IsDevice") == "1" &&
                            TaskAPI.GetVariableBySingleValue("Deposit") != "" && TaskAPI.GetVariableBySingleValue("Deposit") != "0")
                        {
                            if (storeMasterData.MachineDeposit != null)
                            {
                                // ReSharper disable once PossibleInvalidOperationException
                                l_sb_Amount.Text = "满额：" + storeMasterData.MachineDeposit.Value.ToString("N");
                                // ReSharper disable PossibleInvalidOperationException
                                /*去除赋值*/
                                //tb_sb_Amount.Text = storeMasterData.MachineDeposit.Value.ToString("N");
                            }
                        }

                        if (TaskAPI.GetVariableBySingleValue("IsDevice") == "1" && (TaskAPI.GetVariableBySingleValue("DeviceTransfer") != "1"))
                        {
                            l_sb_Amount.Text = storeMasterData.MachineDeposit == null ? "" : "满额：" + storeMasterData.MachineDeposit.Value.ToString("N");
                            //tb_sb_Amount.Text = storeMasterData.MachineDeposit == null ? "" : storeMasterData.MachineDeposit.Value.ToString("N");/*去除赋值*/
                            tb_sb_postingDate.Text = storeMasterData.Channel;
                            l_sb_postingDate.Text = storeMasterData.Channel;
                            tb_sb_payer.Text = storeMasterData.Telephone;
                            l_sb_payer.Text = storeMasterData.Telephone;
                            tb_BuyMachineDeposit.Text = storeMasterData.BuyMachineDeposit == null ? "" : storeMasterData.BuyMachineDeposit.Value.ToString("N");
                            tb_BuyMachineDeposit.Enabled = false;
                            tb_EapproveSN.Text = storeMasterData.EapproveSN;
                            if (_hasDevice)
                            {
                                DispenseModel.SelectedValue = storeMasterData.DispenseModel;
                                ShakerModel.SelectedValue = storeMasterData.ShakerModel;
                                PcModel.SelectedValue = storeMasterData.PcModel;
                            }
                        }

                        #region Finance Margin Confirm

                        if (TaskAPI.Step == "Finance Margin Confirm")
                        {
                            Agreement.Visible = true;
                            tb_zx_Amount.Visible = true;
                            l_fullAmount.Visible = true;

                            var dealer = DealerService.GetById(store.DealerID.Value);
                            var channel = store.Channel ?? dealer.Channel;
                            var cityClass = dealer.CityClass;
                            switch (channel)
                            {
                                case "多乐士":
                                    if (store.CityClass != null)
                                    {
                                        switch (cityClass)
                                        {
                                            case "A":
                                                l_fullAmount.Text = @"满额： 30,000.00";
                                                break;
                                            case "B":
                                                l_fullAmount.Text = @"满额： 20,000.00";
                                                break;
                                            case "C":
                                                l_fullAmount.Text = @"满额： 15,000.00";
                                                break;
                                            default:
                                                l_fullAmount.Text = @"满额： 10,000.00";
                                                break;
                                        }
                                    }
                                    break;
                                case "来威":
                                    l_fullAmount.Text = @"满额： 5,000.00";
                                    break;
                            }

                            if (l_fullAmount.Text == "")
                            {
                                l_fullAmount.Text = @"满额：";
                            }

                            Device.Visible = false;

                        }
                        #endregion

                    }
                    if (TaskAPI.Step == "Renovation")
                    {
                        tr_DeviceTitle.Visible = false;
                        l_fullAmount.Visible = false;
                        deviceManager.Visible = false;
                        tb_fj.Visible = false;
                        tb_Inform_Device.Visible = false;
                        tb_Delivery_Device.Visible = false;
                        tr_address.Visible = false;
                        DispenseModel.Visible = false;
                        ShakerModel.Visible = false;
                        PcModel.Visible = false;
                        tr_threeMode.Visible = false;
                        InitRenovation();
                        hidRenovation.Style.Remove("display");
                        var agreementDeposit = (t_smd_Deposit._AuthID == uc_store1.store.AuthID
                            & t_smd_Deposit._DepositType == "履约保证金"
                                & t_smd_Deposit._StoreID == store.StoreID).ListFirst<t_smd_Deposit>(Storage.Context3);
                        Device.Style.Add("display", "none");
                        l_zx_Amount.Text = Utils.ObjectToStr(agreementDeposit.Amount.ToString("N"));
                        tb_zx_Amount.Visible = false;
                        btn_submit.Text = @"装修启动(Submit)";
                    }
                    else if (TaskAPI.Step == "Inform Delivery Device" || TaskAPI.Step == "Delivery Device")
                    {
                        Logging.GetLogger().Info("======================================================");
                        Logging.GetLogger().Info("進入了發機");
                        Logging.GetLogger().Info("======================================================");

                        tb_sb_postingDate.Visible = false;
                        tb_sb_payer.Visible = false;
                        isSendEmail.Disabled = true;
                        tb_Delivery_Device.Visible = false;

                        InitDeviceModes();

                        DispenseModel.SelectedValue = storeMasterData.DispenseModel;
                        PcModel.SelectedValue = storeMasterData.PcModel;
                        ShakerModel.SelectedValue = storeMasterData.ShakerModel;
                        l_BuyMachineDeposit.Text = storeMasterData.BuyMachineDeposit.Value.ToString("N");
                        l_EapproveSN.Text = storeMasterData.EapproveSN;

                        var deviceDeposit = (t_smd_Deposit._AuthID == uc_store1.store.AuthID
                            & t_smd_Deposit._DepositType == "设备保证金"
                                & t_smd_Deposit._StoreID == store.StoreID).ListFirst<t_smd_Deposit>(Storage.Context3, " DepositId desc ");
                        Logging.GetLogger().Info("保證金null=" + deviceDeposit == null);
                        Logging.GetLogger().Info("storemaster=" + storeMasterData == null);
                        Agreement.Style.Add("display", "none");
                        tb_sb_Amount.Visible = false;
                        l_sb_Amount.Text = Utils.ObjectToStr(deviceDeposit.Amount.ToString("N"));
                        tb_SapDeviceNo.Visible = false;
                        l_SapDeviceNo.Text = deviceDeposit.SapDeviceNo;
                        tb_sb_payer.Visible = false;
                        l_sb_payer.Text = deviceDeposit.Payer;
                        tb_sb_postingDate.Visible = false;
                        l_sb_postingDate.Text = deviceDeposit.PostingDate.HasValue ? deviceDeposit.PostingDate.Value.ToString("yyyy-MM-dd") : "";

                        if (TaskAPI.Step == "Delivery Device")
                        {
                            CKD_list.Visible = true;
                            DispenseModel.Visible = false;
                            ShakerModel.Visible = false;
                            PcModel.Visible = false;

                            l_DispenseModel.Text = storeMasterData.DispenseModel;
                            l_PcModel.Text = storeMasterData.PcModel;
                            l_ShakerModel.Text = storeMasterData.ShakerModel;
                            tb_BuyMachineDeposit.Visible = false;
                            tb_EapproveSN.Visible = false;
                            isSendEmail.Disabled = false;
                            InitDeviceModes();
                            tb_Delivery_Device.Visible = true;

                            dir.Checked = storeMasterData.IsRenew == null ? false : storeMasterData.IsRenew.Value;//存放dir方式
                            SeachStoreId = Storeid.ToString(CultureInfo.InvariantCulture);
                            InitDeliveryType();
                            PurchasedDate.Text = DateTime.Now.ToString("yyyy");
                            //美萍号取最上面一个
                            var meiping = (t_smd_Meiping._SerialNumber != "").ListFirst<t_smd_Meiping>(Storage.Context3, " SerialNumber desc ");
                            Logging.GetLogger().Info("meiping=" + meiping == null);
                            meiPinNo.Value = meiping.SerialNumber;

                            //设备固定资产号自动填
                            tb_address.Text = storeMasterData.Location;//这里存放的是地址
                            tb_ContactNumber.Text = storeMasterData.CreatorStaffCode;//联系电话
                            tb_Contacts.Text = storeMasterData.ContractPerson;//联系人

                            btn_submit.Text = @"确认发机(Submit)";
                        }
                        else
                        {
                            tb_BuyMachineDeposit.Visible = false;
                            tb_EapproveSN.Visible = false;
                            tb_address.Text = store.StoreAddress;
                            InitDeliveryType();
                            tb_Contacts.Text = store.ContactPerson;
                            tb_ContactNumber.Text = store.PhoneNumber;
                            btn_submit.Text = @"通知发机(Submit)";
                            dir.Disabled = true;
                            dir.Checked = storeMasterData.IsRenew ?? false;//存放dir方式
                            if (TaskAPI.GetVariableBySingleValue("DeviceCancel") == "2")
                            {
                                tb_address.Text = storeMasterData.Location;
                                tb_ContactNumber.Text = storeMasterData.CreatorStaffCode;//联系电话
                                tb_Contacts.Text = storeMasterData.ContractPerson;//联系人
                            }
                        }
                    }
                    #endregion


                }
                #endregion
            }
            else
            {
                if (TaskAPI.Step == "Renovation")
                {
                    InitRenovation();
                }
            }
        }

        private bool Send(ref string returnMsg)
        {
            bool flag;
            var summaryStore = uc_store1.store;
            var dealer = DealerService.GetById(summaryStore.DealerID.Value);
            var summary = "|" + summaryStore.AuthID + "|" + dealer.DealerCode;
            try
            {
                #region 数据验证
                if (TaskAPI.Step == "Submit Document" && TaskAPI.IsAllowSubmit) // 如果是退回的情况，不存在验证
                {

                    if (Storeid == 0)
                    {
                        returnMsg = "请选择门店";
                        return false;
                    }

                    #region 必须上传汇款底单
                    var cancel2 = TaskAPI.GetVariableBySingleValue("IsCancel");
                    isTransfer = (cancel2 == "1");
                    if (!ajaxUpload1.IsHaveAttachment && !isTransfer)
                    {
                        /*验证是否是履约保证金流程*/
                        //if (TaskAPI.GetVariableBySingleValue("IsMargin") == "1") { returnMsg = "请上传履约保证金财务确认邮件！"; } else { returnMsg = "请上传汇款底单！"; }
                        returnMsg = "请上传汇款底单！";
                        return false;
                    }
                    #endregion

                    #region 汇款底单不需要必须上传 2015-12-31 by ShenJH

                    //if (TaskAPI.GetVariableBySingleValue("IsDevice") == "1" && DwzAssessment1.Assessment.Opinion != "2" && !ajaxUpload1.IsHaveAttachment)
                    //{
                    //    // 如果是卖场并且设备保证金为0的，不需要验证
                    //    if (uc_store1.store.StoreType != "MT" &&
                    //        Utils.StrToDecimal(l_sb_Amount.Text.Replace(",", ""), 0) > 0)
                    //    {
                    //        returnMsg = "请上传汇款底单";
                    //        return false;
                    //    }
                    //}
                    #endregion

                    if (!CheckInformDevice(out returnMsg))
                    {
                        return false;
                    }

                }

                if (TaskAPI.Step == "Submit Margin Document")
                {
                    #region 必须上传汇款底单

                    //if (!ajaxUpload1.IsHaveAttachment)
                    //{
                    //    returnMsg = "请上传履约保证金财务确认邮件！";
                    //    return false;
                    //}
                    #endregion
                }

                if (TaskAPI.Step == "Finance Confirm")
                {
                    #region 验证履约保证金
                    //if (DwzAssessment1.Assessment.Opinion == "1")
                    //{
                    //    if (TaskAPI.GetVariableBySingleValue("IsRenovation") == "1")
                    //    {
                    //        if (Utils.StrToInt64(tb_zx_Amount.Text.Replace(",", ""), 0) < Utils.StrToInt(l_fullAmount.Text.Split('：')[1].Replace(",", "").Trim(), 0))
                    //        {
                    //            returnMsg = "履约保证金要不能小于满额";
                    //            return false;
                    //        }
                    //    }

                    //}
                    #endregion

                    if (DwzAssessment1.Assessment.Opinion == "0" && DwzAssessment1.Assessment.Remark == "")
                    {
                        returnMsg = "如果退回此流程,请在状态备注中填写退回的原因";
                        return false;
                    }

                    if (DwzAssessment1.Assessment.Opinion == "1" && Utils.StrToInt64(tb_sb_Amount.Text.Replace(",", ""), 0) < Utils.StrToInt(l_sb_Amount.Text.Split('：')[1].Replace(",", "").Trim(), 0))
                    {
                        returnMsg = "设备保证金要不能小于满额";
                        return false;
                    }
                    //Chris wang 2017/8/22 新增设备保证金不能大于满额
                    if (DwzAssessment1.Assessment.Opinion == "1" && Utils.StrToInt64(tb_sb_Amount.Text.Replace(",", ""), 0) > Utils.StrToInt(l_sb_Amount.Text.Split('：')[1].Replace(",", "").Trim(), 0))
                    {
                        returnMsg = "设备保证金不能大于满额，请确认";
                        return false;
                    }

                }
                if (TaskAPI.Step == "Finance Margin Confirm")
                {
                    if (DwzAssessment1.Assessment.Opinion == "1" && Utils.StrToInt64(tb_zx_Amount.Text.Replace(",", ""), 0) < Utils.StrToInt(l_fullAmount.Text.Split('：')[1].Replace(",", "").Trim(), 0))
                    {
                        returnMsg = "履约保证金要不能小于满额";
                        return false;
                    }

                }
                if (TaskAPI.Step == "Renovation")
                {
                    if (AksRequest.GetFormString("RenvotionType") == "")
                    {
                        returnMsg = "请选择装修类型。";
                        return false;
                    }
                }

                /*判断类型*/
                if (TaskAPI.Step == "Inform Delivery Device")
                {

                    if (!CheckInformDevice(out returnMsg))
                    {
                        return false;
                    }
                }

                if (TaskAPI.Step == "Delivery Device" && TaskAPI.IsAllowSubmit)
                {
                    if (meiPinNo.Value == "")
                    {
                        returnMsg = "请选择美萍号";
                        return false;
                    }

                    if (DwzAssessment1.Assessment.Opinion == "2" && DwzAssessment1.Assessment.Remark == "")
                    {
                        returnMsg = "如果退回此流程,请在状态备注中填写退回的原因";
                        return false;
                    }


                }
                #endregion
                #region 引擎传值
                if (TaskAPI.Step == "Submit Document")//|| TaskAPI.Step == "Submit Margin Document"
                {
                    var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    var store = StoreService.GetSmdStoreById(Storeid);
                    // 空的话，是手动发起的流程
                    if (string.IsNullOrEmpty(key) || key == "DeviceIssued")
                    {
                        TaskAPI["BlankVlue"] = Storeid;
                    }
                    TaskAPI["StoreName"] = store != null ? store.StoreName : "";
                    TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;
                    //TaskAPI.Summary = "收款确认/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                    TaskAPI.Summary = "设备保证金财务审核/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;


                    if (DwzAssessment1.Assessment.Opinion == "2")
                    {
                        TaskAPI["DeviceTransfer"] = "1";
                        TaskAPI["IsFinance"] = IsFinance();
                    }
                    else
                    {
                        TaskAPI["DeviceTransfer"] = "2";
                    }

                }
                else
                {
                    TaskAPI["R_Dispense_Vendor_Inform"] = "SCui@idexcorp.com;claire.east.wang@akzonobel.com";
                    var isCancel = TaskAPI.GetVariableBySingleValue("IsCancel");
                    TaskAPI["TaskID"] = TaskAPI.TaskID;
                    switch (TaskAPI.Step)
                    {
                        case "Finance Confirm":
                            TaskAPI["FinanceConfirmed"] = DwzAssessment1.Assessment.Opinion;
                            if (DwzAssessment1.Assessment.Opinion == "1" && IsFinance() == 2)
                            {
                                if (TaskAPI.GetVariableBySingleValue("IsRenovation") == "0")
                                {
                                    TaskAPI.Summary = "通知发机/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                }
                                else if (TaskAPI.GetVariableBySingleValue("IsDevice") == "0")
                                {
                                    TaskAPI.Summary = "装修启动/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                }
                                else
                                {
                                    TaskAPI.Summary = "装修启动或通知发机/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                }
                            }
                            else
                            {
                                if (TaskAPI.GetVariableBySingleValue("IsDevice") == "1")
                                    TaskAPI.Summary = "(设备保证金退回)汇款底单上传/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                            }
                            break;
                        case "Finance Margin Confirm":
                            TaskAPI["FinanceConfirmed"] = DwzAssessment1.Assessment.Opinion;
                            if (DwzAssessment1.Assessment.Opinion == "1" && IsFinance() == 2)
                            {


                                if (TaskAPI.GetVariableBySingleValue("IsRenovation") == "0")
                                {
                                    TaskAPI.Summary = "通知发机/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                }
                                else if (TaskAPI.GetVariableBySingleValue("IsMargin") == "1")
                                {
                                    TaskAPI.Summary = "装修启动/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                }
                                else
                                {
                                    TaskAPI.Summary = "装修启动或通知发机/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                }
                            }
                            else
                            {
                                if (TaskAPI.GetVariableBySingleValue("IsDevice") == "1")
                                    TaskAPI.Summary = "(履约保证金退回)汇款底单上传/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                            }
                            break;
                        case "Inform Delivery Device":
                            if (isCancel == "1" && DwzAssessment1.Assessment.Opinion == "1")
                            {
                                TaskAPI["DeviceCancel"] = DwzAssessment1.Assessment.Opinion;
                                break;
                            }
                            TaskAPI["DeviceCancel"] = "0";
                            TaskAPI.Summary = "确认发机/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                            if (TaskAPI.GetVariableBySingleValue("IsRenovation") == "1")
                            {
                                TaskAPI.Summary = "装修启动或确认发机/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                            }
                            TaskAPI["DeliveryType"] = AksRequest.GetString("DeliveryType");
                            TaskAPI["DeviceAddress"] = tb_address.Text;
                            break;
                        case "Delivery Device":
                            TaskAPI["DeviceCancel"] = DwzAssessment1.Assessment.Opinion;
                            if (DwzAssessment1.Assessment.Opinion == "2")
                            {
                                TaskAPI.Summary = "(退回)通知确认/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                if (TaskAPI.GetVariableBySingleValue("IsRenovation") == "1")
                                {
                                    TaskAPI.Summary = "装修启动或(退回)通知确认/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                                }
                            }
                            break;
                        case "Renovation":
                            var informAss =
                                (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process &
                                 t_Assessment.step == "Inform Delivery Device").ListFirst<t_Assessment>("id desc");
                            var deliveryAss =
                                (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process &
                                 t_Assessment.step == "Delivery Device").ListFirst<t_Assessment>("id desc");



                            if ((deliveryAss != null && deliveryAss.OpinionText.Contains("总部不发机")) || (informAss != null && informAss.OpinionText.Contains("总部不发机")))
                            {
                                TaskAPI["DeviceCancel"] = "1";
                            }
                            else
                            {
                                TaskAPI["DeviceCancel"] = "";
                            }
                            break;
                    }
                }

                #endregion

                #region 提交步骤

                Storage.TransactionExecute(o =>
                {
                    #region 审批意见
                    Logging.GetLogger().Info("======================================================");
                    Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                    Logging.GetLogger().Info("TaskId:" + TaskAPI.TaskID);
                    Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                    Logging.GetLogger().Info("UserAPI.UserFullName:" + UserAPI.UserFullName);
                    Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                    Logging.GetLogger().Info("======================================================");
                    Logging.GetLogger().Info(" ");
                    t_Assessment ass = DwzAssessment1.Assessment;
                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if ((lastAss != null && lastAss.Step != TaskAPI.Step) || lastAss == null)
                    {
                        Storage.Save(Storage.Context1, ass);
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }

                    #endregion

                    #region “Submit Document”步骤
                    if (TaskAPI.Step == "Submit Document")
                    {
                        var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                        var store = (t_smd_Store._StoreID == Storeid).ListFirst<t_smd_Store>(Storage.Context3);
                        decimal _machineDeposit = 0;
                        if (TaskAPI.GetVariableBySingleValue("IsDevice") == "1")
                        {
                            //设备保证金
                            if (Utils.StrToDecimal(l_sb_Amount.Text.Replace(",", ""), 0) <= _machineDeposit)
                            {
                                Logging.GetLogger().Info("machineDeposit_1");
                                if (Utils.StrToDecimal(TaskAPI.GetVariableBySingleValue("Deposit"), 0) > _machineDeposit)
                                {
                                    Logging.GetLogger().Info("machineDeposit_2");
                                    storeMasterData.MachineDeposit = Utils.StrToDecimal(TaskAPI.GetVariableBySingleValue("Deposit"), 0);
                                }
                            }
                            else
                            {
                                Logging.GetLogger().Info("machineDeposit_3");
                                storeMasterData.MachineDeposit = Utils.StrToDecimal(l_sb_Amount.Text.Replace(",", ""), 0);
                            }
                            //storeMasterData.MachineDeposit = Utils.StrToDecimal(l_sb_Amount.Text.Replace(",", ""), 0);
                            //付款人
                            storeMasterData.Telephone = tb_sb_payer.Text;
                            //支付时间
                            storeMasterData.Channel = AksRequest.GetFormString("tb_sb_postingDate").ToString(CultureInfo.InvariantCulture);
                            //SapDocument
                            storeMasterData.SerialNumber = tb_SapDeviceNo.Text;
                            //购机总额
                            storeMasterData.BuyMachineDeposit = Utils.StrToDecimal(tb_BuyMachineDeposit.Text.Replace(",", ""), 0);
                            //设备系统流水号
                            storeMasterData.EapproveSN = tb_EapproveSN.Text;

                        }
                        if (TaskAPI.GetVariableBySingleValue("IsRenovation") == "1")
                        {
                            storeMasterData.DecorativeDeposit = Utils.StrToDecimal(tb_zx_Amount.Text.Replace(",", ""), 0);
                        }

                        if (Utils.StrToDecimal(tb_sb_Amount.Text.Replace(",", ""), 0) <= _machineDeposit)
                        {
                            Logging.GetLogger().Info("machineDeposit_4");
                            if (Utils.StrToDecimal(TaskAPI.GetVariableBySingleValue("Deposit"), 0) > _machineDeposit)
                            {
                                Logging.GetLogger().Info("machineDeposit_5");
                                storeMasterData.MachineDeposit = Utils.StrToDecimal(TaskAPI.GetVariableBySingleValue("Deposit"), 0);
                            }
                        }
                        else
                        {
                            Logging.GetLogger().Info("machineDeposit_6");
                            storeMasterData.MachineDeposit = Utils.StrToDecimal(tb_sb_Amount.Text.Replace(",", ""), 0);
                        }
                        storeMasterData.TotalDeposit = storeMasterData.MachineDeposit + storeMasterData.DecorativeDeposit;

                        storeMasterData.StoreName = store.StoreName;
                        storeMasterData.AuthID = store.AuthID;
                        storeMasterData.AreaName = store.Region;
                        storeMasterData.ProvinceName = store.Province;
                        storeMasterData.CityName = store.CityName;
                        storeMasterData.Address = store.StoreAddress;
                        storeMasterData.BusinessProcess = ass.BusinessProcess;
                        storeMasterData.BusinessKey = ass.BusinessKey;

                        Storage.Save(storeMasterData);
                    }
                    #endregion

                    #region “Finance Confirm”“Finance Margin Confirm”步骤
                    if (TaskAPI.Step == "Finance Confirm" || TaskAPI.Step == "Finance Margin Confirm")
                    {
                        var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);



                        if (DwzAssessment1.Assessment.Opinion == "0")
                        {
                            storeMasterData.Step = "Fill in the request";
                        }
                        else
                        {
                            if (TaskAPI.GetVariableBySingleValue("IsDevice") == "1" && TaskAPI.GetVariableBySingleValue("DeviceTransfer") != "1")
                            {
                                storeMasterData.Step = "Delivery Device";
                                if (TaskAPI.Step == "Finance Confirm")
                                {
                                    SaveDevice(uc_store1.store, true, true, 0);
                                }
                                //设备保证金
                                //storeMasterData.MachineDeposit = Utils.StrToDecimal(l_sb_Amount.Text.Replace(",", ""), 0);
                                //Logging.GetLogger().Info("machineDeposit_8" + storeMasterData.MachineDeposit);

                                decimal _machineDeposit = 0;
                                Logging.GetLogger().Info("l_sb_Amount" + l_sb_Amount.Text);
                                //设备保证金
                                if (Utils.StrToDecimal(tb_sb_Amount.Text.Replace(",", ""), 0) <= _machineDeposit)
                                {
                                    if (Utils.StrToDecimal(TaskAPI.GetVariableBySingleValue("Deposit"), 0) > _machineDeposit)
                                    {
                                        storeMasterData.MachineDeposit = Utils.StrToDecimal(TaskAPI.GetVariableBySingleValue("Deposit"), 0);
                                    }
                                }
                                else
                                {
                                    storeMasterData.MachineDeposit = Utils.StrToDecimal(tb_sb_Amount.Text.Replace(",", ""), 0);
                                }

                                //付款人
                                storeMasterData.Telephone = tb_sb_payer.Text;
                                //支付时间
                                storeMasterData.Channel = tb_sb_postingDate.Text;
                                //SapDocument
                                storeMasterData.SerialNumber = tb_SapDeviceNo.Text;
                                //购机总额
                                storeMasterData.BuyMachineDeposit = Utils.StrToDecimal(tb_BuyMachineDeposit.Text.Replace(",", ""), 0);
                                //设备系统流水号
                                storeMasterData.EapproveSN = tb_EapproveSN.Text;
                                //3个model
                                storeMasterData.DispenseModel = DispenseModel.SelectedValue;
                                storeMasterData.PcModel = PcModel.SelectedValue;
                                storeMasterData.ShakerModel = ShakerModel.SelectedValue;
                            }

                            switch (TaskAPI.GetVariableBySingleValue("IsRenovation"))
                            {
                                case "1":
                                    storeMasterData.Step = "Renovation";
                                    if (TaskAPI.Step == "Finance Margin Confirm")
                                    {
                                        SaveRenovation(uc_store1.store, true, true);
                                    }
                                    break;
                            }

                        }

                        TaskAPI["IsFinance"] = IsFinance();

                        Storage.Save(storeMasterData);
                    }
                    #endregion


                    #region “Renovation”步骤
                    if (TaskAPI.Step == "Renovation")
                    {
                        var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                        storeMasterData.Step = "Finish";

                        Storage.Save(storeMasterData);

                        var store = StoreService.GetSmdStoreById(Storeid);
                        store.StoreStatus = store.StoreReportStatus = "装修启动";
                        storeMasterData.Status = "装修启动";

                        if (store.NewFitment == "翻新" || storeMasterData.NewFitment == "翻新"
                            || store.NewFitment == "从DCSS升级" || storeMasterData.NewFitment == "从DCSS升级")
                        {
                            store.StoreReportStatus = "营业";
                        }
                        //通知邮件发送相关人员
                        sendEmail();


                        Storage.Save(Storage.Context3, store);
                        SaveRenovation(store, false, false);
                    }
                    #endregion

                    #region “Inform Delivery Device”步骤
                    if (TaskAPI.Step == "Inform Delivery Device")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            return;
                        }
                        (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).Edit<t_StoreMasterData>(p =>
                        {
                            //设备地址
                            p.Location = tb_address.Text;
                            //设备保证金
                            p.MachineDeposit = Utils.StrToDecimal(l_sb_Amount.Text.Replace(",", ""), 0);
                            //付款人
                            p.Telephone = l_sb_payer.Text;
                            //支付时间
                            p.Channel = l_sb_postingDate.Text;
                            //SapDocument
                            p.SerialNumber = l_SapDeviceNo.Text;
                            //购机总额
                            p.BuyMachineDeposit = Utils.StrToDecimal(l_BuyMachineDeposit.Text.Replace(",", ""), 0);
                            //设备系统流水号
                            p.EapproveSN = l_EapproveSN.Text;
                            //联系人
                            p.ContractPerson = tb_Contacts.Text;
                            //联系电话
                            p.CreatorStaffCode = tb_ContactNumber.Text;

                            //3个model
                            p.DispenseModel = DispenseModel.SelectedValue;
                            p.PcModel = PcModel.SelectedValue;
                            p.ShakerModel = ShakerModel.SelectedValue;
                            p.IsRenew = dir.Checked;

                        });
                    }
                    #endregion

                    #region “Delivery Device”步骤
                    switch (TaskAPI.Step)
                    {
                        case "Delivery Device":
                            {
                                if (DwzAssessment1.Assessment.Opinion == "1")
                                {
                                    return;
                                }
                                if (DwzAssessment1.Assessment.Opinion == "2")
                                {
                                    return;
                                }
                                var needUpdeviceID = Utils.StrToInt(h_deviceId.Value, 0);
                                var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);

                                storeMasterData.Step = "Finish";
                                storeMasterData.MallName = needUpdeviceID != 0 ? needUpdeviceID.ToString(CultureInfo.InvariantCulture) : "0";
                                storeMasterData.Location = tb_address.Text;
                                if (isSendEmail.Checked)
                                {
                                    storeMasterData.IsColourService = true;
                                }
                                Storage.Save(storeMasterData);
                                var device = (t_smd_Device._FullSetSN == fullSetSN.Value & t_smd_Device._StoreID == Storeid).ListFirst<t_smd_Device>(Storage.Context3);
                                var store = StoreService.GetSmdStoreById(Storeid);
                                if (_hasDevice)
                                {
                                    if (needUpdeviceID != 0)
                                    {
                                        var upDevice = (t_smd_Device._DeviceID == needUpdeviceID).ListFirst<t_smd_Device>(Storage.Context3);
                                        upDevice.NeedUpdate = true;
                                        Storage.Save(Storage.Context3, upDevice);
                                    }

                                    if (device == null)
                                        device = new t_smd_Device();

                                    device.DispenserModel = l_DispenseModel.Text;
                                    device.PcModel = l_PcModel.Text;
                                    device.ShakerModel = l_ShakerModel.Text;
                                    device.Contacts = tb_Contacts.Text;
                                    device.ContactNumber = tb_ContactNumber.Text;
                                    device.BuyMachineDeposit = Utils.StrToDecimal(l_BuyMachineDeposit.Text.ToString(CultureInfo.InvariantCulture).Replace(",", ""), 0);
                                    device.FullSetSN = GetFullSet(AksRequest.GetFormString("DeliveryType"));
                                    if (l_DispenseModel.Text != "" && l_DispenseModel.Text != "不需要")
                                    {
                                        device.DispenserFixedAsset = GetFullSet(AksRequest.GetFormString("DeliveryType")) + "D";
                                    }
                                    if (l_PcModel.Text != "" && l_PcModel.Text != "不需要")
                                    {
                                        device.PcFixedAsset = GetFullSet(AksRequest.GetFormString("DeliveryType")) + "P";
                                    }
                                    if (l_ShakerModel.Text != "" && l_ShakerModel.Text != "不需要")
                                    {
                                        device.ShakerFixedAsset = GetFullSet(AksRequest.GetFormString("DeliveryType")) + "S";
                                    }
                                    device.Status = Cache["Device_SY"].ToString();
                                    device.MeiPinNo = meiPinNo.Value;


                                    device.StoreID = store.StoreID;
                                    device.AuthID = store.AuthID;
                                    device.IsTurnSolid = true;
                                    device.Address = tb_address.Text;
                                    device.EapproveSN = l_EapproveSN.Text;
                                    device.DeliveryType = AksRequest.GetFormString("DeliveryType");
                                    device.DeviceApprovedDate = storeMasterData.DeviceApprovedDate;
                                    device.DIRComputer = dir.Checked;

                                    device.PurchasedDate = Utils.StrToDateTime(PurchasedDate.Text + "-01-01");
                                    Storage.Save(Storage.Context3, device);
                                }

                                _storeDevice = device;

                                if (_storeDevice != null)
                                {
                                    var pcMode = _storeDevice.PcModel ?? "";
                                    var dispenserModel = _storeDevice.DispenserModel ?? "";
                                    var shakerModel = _storeDevice.ShakerModel ?? "";

                                    UpdateInitQuantity(pcMode);
                                    UpdateInitQuantity(dispenserModel);
                                    UpdateInitQuantity(shakerModel);
                                }

                                (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).Edit<t_StoreMasterData>(
                                    p => p.DeviceId = _storeDevice.DeviceID
                                    );
                                (t_smd_Meiping._SerialNumber == meiPinNo.Value).Delete<t_smd_Meiping>(Storage.Context3);
                                SaveDevice(store, false, false, device.DeviceID);

                                var shipOrderlist = (t_smd_ShipOrderNumber._Process == TaskAPI.Process
                                                        & t_smd_ShipOrderNumber._Incident == TaskAPI.Incident).List<t_smd_ShipOrderNumber>(Storage.Context3).ToList();

                                if (shipOrderlist.Count == 0)
                                {
                                    DeliveryOrder(store, _storeDevice, dir.Checked);
                                    shipOrderlist = (t_smd_ShipOrderNumber._Process == TaskAPI.Process
                                                        & t_smd_ShipOrderNumber._Incident == TaskAPI.Incident).List<t_smd_ShipOrderNumber>(Storage.Context3).ToList();
                                }

                                foreach (var shipOrder in shipOrderlist)
                                {
                                    shipOrder.DeviceId = device.DeviceID;
                                }

                                // ReSharper disable once CoVariantArrayConversion
                                Storage.Save(Storage.Context3, shipOrderlist.ToArray());

                                if (isSendEmail.Checked)
                                {
                                    var dispense = shipOrderlist.FirstOrDefault(t => t.Mode.ToLower() == "dispense" && t.Incident == TaskAPI.Incident && t.Process == TaskAPI.Process);
                                    var shaker = shipOrderlist.FirstOrDefault(t => t.Mode.ToLower() == "shaker" && t.Incident == TaskAPI.Incident && t.Process == TaskAPI.Process);
                                    var pc = shipOrderlist.FirstOrDefault(t => t.Mode.ToLower() == "pc" && t.Incident == TaskAPI.Incident && t.Process == TaskAPI.Process);
                                    var ups = shipOrderlist.FirstOrDefault(t => t.Mode.ToLower() == "ups" && t.Incident == TaskAPI.Incident && t.Process == TaskAPI.Process);

                                    TaskAPI["IsVendorInform"] = 1;


                                    if (shaker != null)
                                        TaskAPI["ShakerAttachmentPath"] = Util.AppSettings("path") + @"\" + "CKD" +
                                                                            @"\" +
                                                                            shaker.Name;
                                    else
                                    {
                                        TaskAPI["ShakerAttachmentPath"] = "notNeed";
                                    }
                                    if (dispense != null)
                                        TaskAPI["DispenseAttachmentPath"] = Util.AppSettings("path") + @"\" + "CKD" +
                                                                            @"\" + dispense.Name;
                                    else
                                    {
                                        TaskAPI["DispenseAttachmentPath"] = "notNeed";
                                    }


                                    if (pc != null)
                                        TaskAPI["PcAttachmentPath"] = Util.AppSettings("path") + @"\" + "CKD" + @"\" +
                                                                        pc.Name;
                                    else
                                        TaskAPI["PcAttachmentPath"] = "notNeed";
                                    if (ups != null)
                                        TaskAPI["UpsAttachmentPath"] = Util.AppSettings("path") + @"\" + "CKD" + @"\" + ups.Name;
                                }
                                if (_storeDevice != null)
                                {
                                    TaskAPI["MeipingNumber"] = _storeDevice.MeiPinNo;
                                    TaskAPI["FullsetSN"] = _storeDevice.FullSetSN;
                                }
                                TaskAPI.Summary += "|" + _storeDevice.FullSetSN;
                            };
                            break;
                    }
                    #endregion
                });

                flag = TaskAPI.Send();

                #region 如果数据库写入成功且流程发起成功的情况，将业务表数据与流程实例号进行关联
                if (TaskAPI.Step == "Submit Document")//|| TaskAPI.Step == "Submit Margin Document"
                {
                    (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });

                    (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });
                }
                #endregion

                #region Finish步骤
                Logging.GetLogger().Info("新保证金，发起门店主数据流程0");
                if (_storeDevice == null)
                {
                    _storeDevice = (t_smd_Device._StoreID == Storeid).ListFirst<t_smd_Device>(Storage.Context3, "DeviceID desc");
                }
                Logging.GetLogger().Info("新保证金，发起门店主数据流程0-1");
                string a = IsFinish(TaskAPI.Step) ? "True" : "false";
                Logging.GetLogger().Info("新保证金，发起门店主数据流程0-2" + a + TaskAPI.Step);
                if (IsFinish(TaskAPI.Step))
                {
                    Logging.GetLogger().Info("新保证金，发起门店主数据流程1");
                    BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");
                    var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                    #region add by zsz 2017/7/25
                    string isRen = TaskAPI.GetVariableBySingleValue("IsRenovation");
                    string isDevice = TaskAPI.GetVariableBySingleValue("IsDevice");
                    #region add by chris 2017/8/16
                    if (storeMasterData.NewFitment.IndexOf("仅调色机申请") != -1)
                    {
                        BusinessService.SaveSycnMappingOrBusinesskey(isRen, isDevice, storeMasterData.BusinessKey);
                    }
                    #endregion
                    #endregion
                    var store = StoreService.GetSmdStoreById(Storeid);
                    var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    var deviceCancel = TaskAPI.GetVariableBySingleValue("DeviceCancel");
                    var deviceTransfer = TaskAPI.GetVariableBySingleValue("DeviceTransfer");
                    var isFinan = TaskAPI.GetVariableBySingleValue("IsFinance");
                    var device = new t_smd_Device();
                    if (_hasDevice && deviceCancel != "1" && deviceTransfer != "1" && isFinan != "2")
                    {
                        device = DeviceService.GetSmdDeviceById(_storeDevice.DeviceID);
                        BusinessService.saveProcessRelation(TaskAPI, DwzAssessment1.Assessment, store, device,
                            dealer, null, null, null, null);
                    }
                    else
                    {
                        BusinessService.saveProcessRelation(TaskAPI, DwzAssessment1.Assessment, store, null, dealer, null, null, null, null);
                    }
                    // 如果是空，就是手动发起的流程
                    if (string.IsNullOrEmpty(key)) return true;

                    // 新开门店自动发起流程
                    if (key == Constant.PROCESS_STORE)
                    {
                        Logging.GetLogger().Info("新保证金，发起门店主数据流程2");
                        #region 自动启动门店信息变更
                        TaskAPI[] taskApi = { new TaskAPI(TaskHelper.STORE_DATA_CHANGE_TASKID) };
                        var applicationNo = GenerateApplicationNo(taskApi[0]);

                        taskApi[0]["ParentProcess"] = TaskAPI.Process;
                        taskApi[0]["ParentIncident"] = TaskAPI.Incident;
                        taskApi[0]["AutoBusinessKey"] = key;
                        taskApi[0]["BlankVlue"] = Storeid;
                        taskApi[0]["Actions"] = "ChangeStore";
                        if (_hasDevice && deviceCancel != "1" && deviceTransfer != "1" && isFinan != "2")
                        {
                            taskApi[0]["DeviceID"] = _storeDevice.DeviceID;
                        }
                        else
                        {
                            taskApi[0]["DeviceID"] = "0";
                        }
                        taskApi[0].InitAutoTask(applicationNo);
                        taskApi[0].Summary = "提交门店信息变更/" + TaskHelper.getSummary(TaskAPI.Summary);
                        taskApi[0].SetStoreDataChangeRecipient(store.Region, store.Province, "Store");
                        // ReSharper disable once InvokeAsExtensionMethod
                        var ass = TaskHelper.InitAutoAssessment(taskApi[0]);
                        Logging.GetLogger().Info("新保证金，发起门店主数据流程3");
                        if (storeMasterData.NewFitment != "仅调色机申请")
                        {
                            if (taskApi[0].Send())
                            {
                                ass = TaskHelper.InitAutoAssessment(taskApi[0]);
                                Storage.Save(Storage.Context1, ass);
                                BusinessService.SaveChildProcess(taskApi[0], ass, "active");
                            }

                            (t_Assessment.process == taskApi[0].Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                            {
                                p.Incident = taskApi[0].Incident;
                            });
                        }
                        #endregion
                        Logging.GetLogger().Info("新保证金，发起门店主数据流程4");
                        if (!storeMasterData.NewFitment.Contains("升级")) //2016-11-28 Add升级无需发起合同流程
                        {
                            if ((storeMasterData.NewFitment == "翻新" && TaskAPI.GetVariableBySingleValue("IsDevice") == "1" && deviceCancel != "1" && deviceTransfer != "1")
                                || (storeMasterData.NewFitment == "仅调色机申请" && deviceCancel != "1" && deviceTransfer != "1") || ((storeMasterData.NewFitment != "翻新") && (storeMasterData.NewFitment != "仅调色机申请")))
                            {
                                //门店类型MT的才发起合同流程
                                if (store.StoreType == "MT")
                                {
                                    #region 自动启动合同信息变更

                                    taskApi[0] = new TaskAPI(TaskHelper.STORE_DATA_CHANGE_TASKID);
                                    applicationNo = GenerateApplicationNo(taskApi[0]);

                                    taskApi[0]["ParentProcess"] = TaskAPI.Process;
                                    taskApi[0]["ParentIncident"] = TaskAPI.Incident;
                                    taskApi[0]["AutoBusinessKey"] = key;
                                    if (_hasDevice && deviceCancel != "1" && deviceTransfer != "1" && isFinan != "2")
                                    {
                                        taskApi[0]["DeviceID"] = _storeDevice.DeviceID;
                                    }
                                    taskApi[0]["BlankVlue"] = TaskAPI.GetStoreId("storeid");
                                    taskApi[0]["Actions"] = "ChangeContract";
                                    taskApi[0].InitAutoTask(applicationNo);
                                    taskApi[0].Summary = "提交合同信息变更/" + TaskHelper.getSummary(TaskAPI.Summary);
                                    taskApi[0].SetStoreDataChangeRecipient(store.Region, store.Province, "Contract");

                                    if (taskApi[0].Send())
                                    {
                                        ass = TaskHelper.InitAutoAssessment(taskApi[0]);
                                        Storage.Save(Storage.Context1, ass);
                                        BusinessService.SaveChildProcess(taskApi[0], ass, "active");
                                    }

                                    (t_Assessment.process == taskApi[0].Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                                    {
                                        p.Incident = taskApi[0].Incident;
                                    });

                                    var storeMasterdate = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                                    if (storeMasterdate.NewFitment.Contains("升级") && !storeMasterdate.NewFitment.Contains("从IS升级"))
                                    {
                                        //签终止协议。
                                        var contract = ContractService.GetContractByStoreID(TaskAPI.GetStoreId("storeid")) ?? new t_smd_Contract
                                        {
                                            AuthID = store.AuthID,
                                            StoreID = store.StoreID
                                        };
                                        var contractCancel = ContractService.GetContractCancel(contract);
                                        var oldContract = ContractService.GetOldContract(contract);
                                        oldContract.StoreCancelContractType = contract.StoreContractType;
                                        Storage.Save(Storage.Context3, oldContract);
                                        Storage.Save(Storage.Context3, contractCancel);
                                        //(t_smd_Contract._ContractID == contract.ContractID).Delete<t_smd_Contract>(Storage.Context3);
                                        contract = ContractService.GetNewContract(contract, false);
                                        contract.StoreNature = "";
                                        Storage.Save(Storage.Context3, contract);
                                    }

                                    #endregion
                                }
                            }
                        }
                    }
                }
                #endregion
                #endregion

            }
            catch (Exception ex)
            {

                returnMsg = ex.Message.Replace("\"", "\\\"");
                Logging.GetLogger().Error("调用NewReceiveDeposit.aspx方法Send_Click出错：" + ex);
                flag = false;
            }

            return flag;
        }

        #region 根据TaskAPI里面的值判断保证金类型
        protected void SetDepositType()
        {
            if (TaskAPI.Step == "Submit Margin Document")
            {
                Device.Style.Add("display", "none");
                deviceManager.Visible = false;
                tb_fj.Visible = false;
                tb_Inform_Device.Visible = false;
                tb_Delivery_Device.Visible = false;
                tr_address.Visible = false;
                tr_DeviceTitle.Visible = false;
                tr_threeMode.Visible = false;
            }

        }
        #endregion

        #region 加载下拉框数据

        // ReSharper disable once InconsistentNaming
        readonly ConfigService configService = new ConfigService();

        #region 加载门店装修类型
        protected void InitRenovation()
        {
            RencovationType = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_MDZXLX')").Tables[0];
        }
        #endregion

        #region 加载设备发放方式
        protected void InitDeliveryType()
        {
            DeliveryType = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_FFFS')").Tables[0];
        }
        #endregion

        #region 加载设备modes
        protected void InitDeviceModes()
        {
            #region 调色机型号
            var dtDispenseModel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_TSJLX') order by seq").Tables[0];
            DispenseModel.AppendDataBoundItems = true;
            foreach (DataRow row in dtDispenseModel.Rows)
            {
                DispenseModel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 震荡机型号
            var dtShakerModel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_ZDJLX') order by seq").Tables[0];
            ShakerModel.AppendDataBoundItems = true;
            foreach (DataRow row in dtShakerModel.Rows)
            {
                ShakerModel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 电脑型号
            var dtPcModel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_DNXH') order by seq").Tables[0];
            PcModel.AppendDataBoundItems = true;
            foreach (DataRow row in dtPcModel.Rows)
            {
                PcModel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion
        }
        #endregion

        #endregion

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            var returnMsg = string.Empty;
            if (Send(ref returnMsg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
                uc_store1.Visible = false;
                return;
            }
            returnMsg = string.IsNullOrEmpty(returnMsg) ? Resources.Global.C_00_Failed : returnMsg;
            ScriptManager.RegisterStartupScript(this, GetType(), "info_tip", "$.jBox.prompt('" + returnMsg + "','提示', 'info');", true);
        }

        #region 保存设备保证金主数据
        /**
         * isConfirm 用来表示是否存日期
         **/
        protected void SaveDevice(t_smd_Store store, bool isConfirm, bool isNew, int deviceID)
        {

            var deviceDeposit = new t_smd_Deposit();

            if (!isNew)
            {
                deviceDeposit = (t_smd_Deposit._StoreID == Storeid & t_smd_Deposit._AuthID == store.AuthID & t_smd_Deposit._DepositType == "设备保证金")
                    .ListFirst<t_smd_Deposit>(Storage.Context3, "depositID desc");
            }

            deviceDeposit.AuthID = store.AuthID;
            deviceDeposit.StoreID = store.StoreID;
            deviceDeposit.Amount = Utils.StrToDecimal(tb_sb_Amount.Text.Replace(",", ""), 0);
            deviceDeposit.DepositType = "设备保证金";
            if (isConfirm)
            {
                deviceDeposit.PostingDate = DateTime.Now;
                deviceDeposit.SapDeviceNo = tb_SapDeviceNo.Text;
                deviceDeposit.Payer = tb_sb_payer.Text;
                deviceDeposit.PostingDate = Utils.StrToDateTime(tb_sb_postingDate.Text);
            }
            if (deviceID != 0)
            {
                deviceDeposit.DeviceID = deviceID;
                deviceDeposit.Amount = Utils.StrToDecimal(l_sb_Amount.Text.Replace(",", ""), 0);
                deviceDeposit.DealerId = store.DealerID.Value;
            }

            Storage.Save(Storage.Context3, deviceDeposit);
        }
        #endregion

        #region 保存履约保证金主数据
        /**
         * isConfirm 用来表示是否存日期
         **/
        protected void SaveRenovation(t_smd_Store store, bool isConfirm, bool isNew)
        {

            var agreeDeposit = new t_smd_Deposit();

            if (!isNew)
            {
                agreeDeposit = (t_smd_Deposit._DepositType == "履约保证金" & t_smd_Deposit._AuthID == store.AuthID & t_smd_Deposit._StoreID == store.StoreID).ListFirst<t_smd_Deposit>(Storage.Context3);
                agreeDeposit.RenovationType = AksRequest.GetFormString("RenvotionType");
            }
            else
            {
                if (isConfirm)
                {
                    agreeDeposit.PostingDate = DateTime.Now;
                }
                agreeDeposit.AuthID = store.AuthID;
                agreeDeposit.StoreID = store.StoreID;
                agreeDeposit.Amount = Utils.StrToDecimal(tb_zx_Amount.Text.Replace(",", ""), 0);
                agreeDeposit.DepositType = "履约保证金";
            }

            Storage.Save(Storage.Context3, agreeDeposit);
        }
        #endregion

        private bool IsFinish(string step)
        {
            var isRenovation = TaskAPI.GetVariableBySingleValue("IsRenovation");
            var isDevice = TaskAPI.GetVariableBySingleValue("IsDevice");
            var deviceCancel = TaskAPI.GetVariableBySingleValue("DeviceCancel");
            var deviceTransfer = TaskAPI.GetVariableBySingleValue("DeviceTransfer");
            var isFin = TaskAPI.GetVariableBySingleValue("IsFinance");
            var isFin2 = TaskAPI.GetVariableBySingleValue("IsFinance2");
            var storemasterdata = StoreMasterDataService.GetByTaskAPI(TaskAPI);
            Logging.GetLogger().Info(string.Format("isRenovation:{0},isDevice:{1},deviceCancel:{2},deviceTransfer:{3},isFin:{4},isFin2:{5}", isRenovation, isDevice, deviceCancel, deviceTransfer, isFin, isFin2));
            switch (step)
            {
                case "Submit Document":
                    if (deviceTransfer == "1" && storemasterdata.NewFitment == "仅调色机申请")
                    {
                        return true;
                    }
                    return false;
                case "Inform Delivery Device":
                    if (deviceCancel == "1")
                    {
                        if (isRenovation == "1")
                        {
                            var task = TaskHelper.GetTask(TaskAPI.Process, TaskAPI.Incident, "Renovation");
                            return task.nTaskStatus == TaskStatuses.TASK_STATUS_COMPLETED;
                        }
                        return true;
                    }
                    return false;
                case "Delivery Device":
                    if (isRenovation == "1")
                    {
                        Logging.GetLogger().Info("test0");
                        var task = TaskHelper.GetTask(TaskAPI.Process, TaskAPI.Incident, "Renovation");
                        Logging.GetLogger().Info("test1" + task);
                        if (task == null)
                        {
                            return false;
                        }//chriswang 10.29
                        return task.nTaskStatus == TaskStatuses.TASK_STATUS_COMPLETED;
                    }
                    if (DwzAssessment1.Assessment.Opinion == "1" || DwzAssessment1.Assessment.Opinion == "2")
                    {
                        return false;
                    }
                    return true;
                case "Renovation":
                    if (isDevice == "1")
                    {
                        Logging.GetLogger().Info("新保证金，发起门店主数据流程1-1");
                        var task = TaskHelper.GetTask(TaskAPI.Process, TaskAPI.Incident, "Delivery Device");
                        Logging.GetLogger().Info("新保证金，发起门店主数据流程1-2");
                        if (deviceCancel == "1")
                        {
                            return true;
                        }
                        Logging.GetLogger().Info("新保证金，发起门店主数据流程1-3");
                        if (deviceTransfer == "1")
                        {
                            return true;
                        }
                        Logging.GetLogger().Info("新保证金，发起门店主数据流程1-4:" + deviceTransfer);
                        Logging.GetLogger().Info("新保证金，发起门店主数据流程1-4");
                        if (isFin == "2" && isFin2 == "1")  //新增判断，用于校验，全新门店 旧机转移类型单据
                        {
                            return true;
                        }
                        if (task == null)
                        {
                            return false;
                        }                       
                        Logging.GetLogger().Info("新保证金，发起门店主数据流程1-5");
                        Logging.GetLogger().Info("新保证金，发起门店主数据流程1-6:" + task.nTaskStatus.ToString());
                        return task.nTaskStatus == TaskStatuses.TASK_STATUS_COMPLETED;

                    }
                    return true;
                default:
                    return false;
            }

        }

        #region 生成出库单
        /**
         * device等于空是自动生成的 
         */
        private void DeliveryOrder(t_smd_Store store, t_smd_Device device, bool qt)
        {
            var needQT = true;
            var address = AksRequest.GetFormString("Address");
            var dealerName = AksRequest.GetFormString("DealerName");
            var contactNumber = AksRequest.GetFormString("ContactNumber");
            var contacts = AksRequest.GetFormString("Contacts");
            var orderProcess = AksRequest.GetFormString("process");
            var orderIncident = AksRequest.GetFormString("incident");
            var orderPcModel = AksRequest.GetFormString("PcModel");
            var shakerModel = AksRequest.GetFormString("ShakerModel");
            var dispenseModel = AksRequest.GetFormString("DispenseModel");
            var purchasedDate = DateTime.Now.ToString("yyyy-MM-dd");
            var deliveryType = AksRequest.GetFormString("DeliveryType");
            var dealer = DealerService.GetById(store.DealerID.Value);
            var dir = AksRequest.GetFormString("quanTao");
            var postingDate = AksRequest.GetFormString("PostingDate");
            var payer = AksRequest.GetFormString("Payer");
            if (dir == "checked")
                needQT = false;
            var decorate = "";
            if (store.StoreType == "MT" || (store.Channel != null && store.Channel == "多乐士") ||
                (dealer.Channel == "多乐士"))
            {
                decorate = "用多乐士装饰";
            }
            else
            {
                decorate = "用来威装饰";
            }


            if (device != null)
            {
                address = device.Address;
                contactNumber = device.ContactNumber;
                contacts = device.Contacts;
                orderProcess = TaskAPI.Process;
                orderIncident = TaskAPI.Incident.ToString(CultureInfo.InvariantCulture);
                orderPcModel = device.PcModel;
                shakerModel = device.ShakerModel;
                dispenseModel = device.DispenserModel;
                if (store != null)
                {
                    dealerName = DealerService.GetById(store.DealerID ?? store.DealerID.Value).Name;
                }

                deliveryType = device.DeliveryType;
                needQT = qt;
            }

            (t_smd_ShipOrderNumber._Process == orderProcess & t_smd_ShipOrderNumber._Incident == orderIncident)
                .Delete<t_smd_ShipOrderNumber>(Storage.Context3);


            IWorkbook hssfworkbook;
            ISheet sheet;

            var shipNumber = (t_smd_ShipOrderNumber._YearOn == DateTime.Now.Year).ListFirst<t_smd_ShipOrderNumber>(Storage.Context3, "Sequence desc");
            string number;
            var sequence = shipNumber != null ? shipNumber.Sequence : 0;
            sequence++;
            var i = 0;
            var baseRow = 15;
            var path = Util.AppSettings("path") + @"\" + "CKD" + @"\";
            FileStream fs;

            if (needQT)
            {
                if (dispenseModel != "" && !dispenseModel.Contains("不需要"))
                {
                    #region 生成调色机出货通知单

                    using (
                        var file = new FileStream(Server.MapPath("~/") + "Pages\\SMD\\Excel\\Dispense.xls",
                            FileMode.Open, FileAccess.Read))
                    {
                        hssfworkbook = WorkbookFactory.Create(file);
                    }
                    sheet = hssfworkbook.GetSheetAt(0);
                    number = DateTime.Now.Year + sequence.ToString(CultureInfo.InvariantCulture).PadLeft(4, '0');
                    sheet.GetRow(0).GetCell(1).SetCellValue(decorate);
                    sheet.GetRow(4).GetCell(3).SetCellValue(number);
                    sheet.GetRow(9).GetCell(1).SetCellValue(dealerName);
                    sheet.GetRow(10).GetCell(1).SetCellValue("地址：" + address);
                    sheet.GetRow(11).GetCell(1).SetCellValue("电话：" + contactNumber);
                    sheet.GetRow(12).GetCell(1).SetCellValue("联系人：" + contacts);
                    sheet.GetRow(13).GetCell(1).SetCellValue("汇款时间：" + postingDate);
                    sheet.GetRow(14).GetCell(1).SetCellValue("付款人：" + payer);
                    sheet.GetRow(16).GetCell(1).SetCellValue(purchasedDate);
                    i = 0;
                    baseRow = 20;
                    if (!string.IsNullOrEmpty(dispenseModel))
                    {
                        sheet.GetRow(baseRow).GetCell(0).SetCellValue(++i);
                        sheet.GetRow(baseRow).GetCell(1).SetCellValue("调色机");
                        sheet.GetRow(baseRow).GetCell(2).SetCellValue(dispenseModel);
                        sheet.GetRow(baseRow).GetCell(3).SetCellValue(1);
                        // ReSharper disable RedundantAssignment
                        baseRow++;
                    }

                    sheet.GetRow(45).GetCell(1).SetCellValue(DateTime.Now.ToString("yyyy/MM/dd"));
                    path = Util.AppSettings("path") + @"\" + "CKD" + @"\";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    fs = File.Create(path + "调色机" + number + "出库单-" + deliveryType + ".xls");
                    hssfworkbook.Write(fs);
                    fs.Close();

                    var shipDispense = new t_smd_ShipOrderNumber
                    {
                        Mode = "Dispense",
                        Name = "调色机" + number + "出库单-" + deliveryType + ".xls",
                        YearOn = DateTime.Now.Year,
                        Sequence = sequence,
                        Process = orderProcess,
                        Incident = Utils.StrToInt(orderIncident, 0)
                    };

                    Storage.Save(Storage.Context3, shipDispense);

                    #endregion
                }

                if (shakerModel != "" && !shakerModel.Contains("不需要"))
                {
                    #region 生成shaker出货通知单
                    sequence++;
                    using (var file = new FileStream(Server.MapPath("~/") + "Pages\\SMD\\Excel\\shaker.xls", FileMode.Open, FileAccess.Read))
                    {
                        hssfworkbook = WorkbookFactory.Create(file);
                    }
                    sheet = hssfworkbook.GetSheetAt(0);
                    number = DateTime.Now.Year + sequence.ToString(CultureInfo.InvariantCulture).PadLeft(4, '0');
                    sheet.GetRow(0).GetCell(1).SetCellValue(decorate);
                    sheet.GetRow(4).GetCell(3).SetCellValue(number);
                    sheet.GetRow(9).GetCell(1).SetCellValue(dealerName);
                    sheet.GetRow(10).GetCell(1).SetCellValue("地址：" + address);
                    sheet.GetRow(11).GetCell(1).SetCellValue("电话：" + contactNumber);
                    sheet.GetRow(12).GetCell(1).SetCellValue("联系人：" + contacts);
                    sheet.GetRow(13).GetCell(1).SetCellValue("汇款时间：" + postingDate);
                    sheet.GetRow(14).GetCell(1).SetCellValue("付款人：" + payer);
                    sheet.GetRow(16).GetCell(1).SetCellValue(purchasedDate);
                    i = 0;
                    baseRow = 20;
                    if (!string.IsNullOrEmpty(shakerModel))
                    {
                        sheet.GetRow(baseRow).GetCell(0).SetCellValue(++i);
                        sheet.GetRow(baseRow).GetCell(1).SetCellValue("震荡机");
                        sheet.GetRow(baseRow).GetCell(2).SetCellValue(shakerModel);
                        sheet.GetRow(baseRow).GetCell(3).SetCellValue(1);
                        baseRow++;
                    }

                    sheet.GetRow(46).GetCell(1).SetCellValue(DateTime.Now.ToString("yyyy/MM/dd"));
                    path = Util.AppSettings("path") + @"\" + "CKD" + @"\";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    fs = File.Create(path + "震荡机" + number + "出库单-" + deliveryType + ".xls");
                    hssfworkbook.Write(fs);
                    fs.Close();


                    var shipShaker = new t_smd_ShipOrderNumber
                    {
                        Mode = "Shaker",
                        Name = "震荡机" + number + "出库单-" + deliveryType + ".xls",
                        YearOn = DateTime.Now.Year,
                        Sequence = sequence,
                        Process = orderProcess,
                        Incident = Utils.StrToInt(orderIncident, 0)
                    };

                    Storage.Save(Storage.Context3, shipShaker);

                    #endregion
                }
            }


            if (orderPcModel != "" && !orderPcModel.Contains("不需要"))
            {
                #region 生成PC出货通知单

                sequence++;
                using (
                    var file = new FileStream(Server.MapPath("~/") + "Pages\\SMD\\Excel\\pc.xls", FileMode.Open,
                        FileAccess.Read))
                {
                    hssfworkbook = WorkbookFactory.Create(file);
                }
                sheet = hssfworkbook.GetSheetAt(0);
                number = DateTime.Now.Year + sequence.ToString(CultureInfo.InvariantCulture).PadLeft(4, '0');
                sheet.GetRow(0).GetCell(1).SetCellValue(decorate);
                sheet.GetRow(4).GetCell(3).SetCellValue(number);
                sheet.GetRow(6).GetCell(1).SetCellValue(dealerName);
                sheet.GetRow(7).GetCell(1).SetCellValue("地址：" + address);
                sheet.GetRow(8).GetCell(1).SetCellValue("电话：" + contactNumber);
                sheet.GetRow(9).GetCell(1).SetCellValue("联系人：" + contacts);
                sheet.GetRow(10).GetCell(1).SetCellValue("汇款时间：" + postingDate);
                sheet.GetRow(11).GetCell(1).SetCellValue("付款人：" + payer);
                sheet.GetRow(13).GetCell(1).SetCellValue(purchasedDate);

                baseRow = 17;
                if (!string.IsNullOrEmpty(orderPcModel))
                {
                    sheet.GetRow(baseRow).GetCell(0).SetCellValue(++i);
                    sheet.GetRow(baseRow).GetCell(1).SetCellValue("电脑主机");
                    sheet.GetRow(baseRow).GetCell(2).SetCellValue(orderPcModel);
                    sheet.GetRow(baseRow).GetCell(3).SetCellValue(1);
                    baseRow++;
                }
                if (!string.IsNullOrEmpty(orderPcModel))
                {
                    sheet.GetRow(baseRow).GetCell(0).SetCellValue(++i);
                    sheet.GetRow(baseRow).GetCell(1).SetCellValue("电脑显示器");
                    sheet.GetRow(baseRow).GetCell(2).SetCellValue(orderPcModel);
                    sheet.GetRow(baseRow).GetCell(3).SetCellValue(1);
                    baseRow++;
                }

                sheet.GetRow(43).GetCell(1).SetCellValue(DateTime.Now.ToString("yyyy/MM/dd"));

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                fs = File.Create(path + "PC" + number + "出库单.xls");
                hssfworkbook.Write(fs);
                fs.Close();

                var pcShip = new t_smd_ShipOrderNumber
                {
                    Mode = "pc",
                    Name = "PC" + number + "出库单.xls",
                    YearOn = DateTime.Now.Year,
                    Sequence = sequence,
                    Process = orderProcess,
                    Incident = Utils.StrToInt(orderIncident, 0)
                };
                Storage.Save(Storage.Context3, pcShip);

                #endregion

                if (deliveryType != "DIT")
                {
                    #region 生成ups出货通知单

                    sequence++;
                    using (
                        var file = new FileStream(Server.MapPath("~/") + "Pages\\SMD\\Excel\\ups.xls", FileMode.Open,
                            FileAccess.Read))
                    {
                        hssfworkbook = WorkbookFactory.Create(file);
                    }
                    sheet = hssfworkbook.GetSheetAt(0);

                    number = DateTime.Now.Year + sequence.ToString(CultureInfo.InvariantCulture).PadLeft(4, '0');
                    sheet.GetRow(0).GetCell(1).SetCellValue(decorate);
                    sheet.GetRow(4).GetCell(3).SetCellValue(number);
                    sheet.GetRow(6).GetCell(1).SetCellValue(dealerName);
                    sheet.GetRow(7).GetCell(1).SetCellValue("地址：" + address);
                    sheet.GetRow(8).GetCell(1).SetCellValue("电话：" + contactNumber);
                    sheet.GetRow(9).GetCell(1).SetCellValue("联系人：" + contacts);
                    sheet.GetRow(10).GetCell(1).SetCellValue("回款时间：" + postingDate);
                    sheet.GetRow(11).GetCell(1).SetCellValue("付款人：" + payer);
                    sheet.GetRow(13).GetCell(1).SetCellValue(purchasedDate);
                    sheet.GetRow(41).GetCell(1).SetCellValue(DateTime.Now.ToString("yyyy/MM/dd"));
                    path = Util.AppSettings("path") + @"\" + "CKD" + @"\";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    fs = File.Create(path + "UPS" + number + "出库单.xls");
                    hssfworkbook.Write(fs);
                    fs.Close();


                    var shipUps = new t_smd_ShipOrderNumber
                    {
                        Mode = "ups",
                        Name = "UPS" + number + "出库单.xls",
                        YearOn = DateTime.Now.Year,
                        Sequence = sequence,
                        Process = orderProcess,
                        Incident = Utils.StrToInt(orderIncident, 0)
                    };
                    Storage.Save(Storage.Context3, shipUps);

                    #endregion
                }
                
            }


        }
        #endregion

        private void ShowNeedForm()
        {
            if (NeedRenovation && !NeedDevice)
            {
                tr_DeviceTitle.Visible = false;
                deviceManager.Visible = false;
                tb_fj.Visible = false;
                tb_Inform_Device.Visible = false;
                tb_Delivery_Device.Visible = false;
                tr_address.Visible = false;
                DispenseModel.Visible = false;
                ShakerModel.Visible = false;
                PcModel.Visible = false;
                Device.Visible = false;
                tr_threeMode.Visible = false;
            }

            if (NeedDevice && !NeedRenovation)
            {
                l_fullAmount.Visible = false;
                tb_sb_postingDate.Visible = false;
                tb_sb_payer.Visible = false;
                isSendEmail.Disabled = true;
                tb_Delivery_Device.Visible = true;
                l_zx_Amount.Visible = false;
                Agreement.Visible = false;
                hidRenovation.Visible = false;
                tb_zx_Amount.Visible = false;
            }
        }

        #region 只读表单
        private bool ReadOnly()
        {
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);

                assessment.Visible = true;
                btn_submit.Visible = false;
                ajaxUpload1.AllowUpload = false;
                ajaxUpload1.AllowDelete = false;
                DwzAssessment1.Visible = false;
                tb_BuyMachineDeposit.Visible = false;
                tb_EapproveSN.Visible = false;
                tb_ContactNumber.Visible = false;
                tb_SapDeviceNo.Visible = false;
                tb_BuyMachineDeposit.Visible = false;
                tb_address.Visible = false;
                CKD_list.Visible = true;
                DispenseModel.Visible = false;
                ShakerModel.Visible = false;
                PcModel.Visible = false;
                uc_store1.IsCanEditAuthID = false;
                fullSetSN.Visible = false;
                meiPinNo.Visible = false;
                PurchasedDate.Visible = false;
                tb_zx_Amount.Visible = false;
                tb_sb_Amount.Visible = false;
                tb_sb_payer.Visible = false;
                l_zx_Amount.Visible = false;
                tb_sb_postingDate.Visible = false;
                tb_Contacts.Visible = false;
                tb_ContactNumber.Visible = false;
                tb_EapproveSN.Visible = false;
                tb_Contacts.Visible = false;
                tb_ContactNumber.Visible = false;
                isSendEmail.Disabled = true;
                cb_needUpdate.Disabled = true;
                dir.Disabled = true;

                var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                uc_store1.store = StoreService.GetSmdStoreById(storeMasterData.StoreId.Value);


                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");
                if (storeMasterData.SubmitDate != null)
                    uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                hidRenovation.Style.Remove("display");
                l_DispenseModel.Text = storeMasterData.DispenseModel;
                l_PcModel.Text = storeMasterData.PcModel;
                l_ShakerModel.Text = storeMasterData.ShakerModel;
                l_sb_Amount.Text = storeMasterData.MachineDeposit == null ? "" : storeMasterData.MachineDeposit.ToString();
                l_Contacts.Text = storeMasterData.Telephone;
                l_sb_postingDate.Text = storeMasterData.Channel;
                l_ContactNumber.Text = storeMasterData.CreatorStaffCode;
                l_SapDeviceNo.Text = storeMasterData.SerialNumber;
                ShowNeedForm();
                if (storeMasterData.BuyMachineDeposit.HasValue)
                {
                    l_BuyMachineDeposit.Text = storeMasterData.BuyMachineDeposit.Value.ToString("N");
                }
                if (storeMasterData.IsColourService == true)
                {
                    isSendEmail.Checked = true;
                }

                ckd_btn.Visible = false;
                l_address.Text = storeMasterData.Location;
                l_sb_payer.Text = storeMasterData.Telephone;
                l_EapproveSN.Text = storeMasterData.EapproveSN;
                l_ContactNumber.Text = storeMasterData.CreatorStaffCode;
                if (storeMasterData.DecorativeDeposit.HasValue)
                {
                    l_zx_Amount.Text = storeMasterData.DecorativeDeposit.Value.ToString("N");
                }
                dir.Checked = storeMasterData.IsRenew == null ? false : storeMasterData.IsRenew.Value;
                t_smd_Device device = DeviceService.GetSmdDeviceById(storeMasterData.DeviceId.HasValue ? storeMasterData.DeviceId.Value : 0);
                t_smd_Deposit storeDeposit = DepositService.GetDepostByStoreid(Storeid);
                if (storeDeposit != null)
                {
                    l_RenovationType.Text = storeDeposit.RenovationType;
                }
                if (storeMasterData.MallName != null && storeMasterData.MallName != "0" && storeMasterData.MallName != "")
                {
                    t_smd_Device upDevice = DeviceService.GetSmdDeviceById(Utils.StrToInt(storeMasterData.MallName, 0));
                    cb_needUpdate.Checked = true;
                    oldDevieSN.InnerText = "      固定资产号：" + upDevice.FullSetSN + "的设备将被更新";
                }

                if (device != null)
                {
                    l_DeliveryType.Text = device.DeliveryType;
                    l_FullSetSN.Text = device.FullSetSN;
                    l_meiPinNo.Text = device.MeiPinNo;
                    if (device.PurchasedDate != null && device.PurchasedDate.HasValue)
                    {
                        PurchasedDate.Text = device.PurchasedDate.Value.ToString("yyyy");
                        l_PurchasedDate.Text = device.PurchasedDate.Value.ToString("yyyy");
                    }
                }
                if (storeDeposit != null)
                {
                    l_fullAmount.Text = storeDeposit.Amount.ToString("N");
                    l_RenovationType.Text = storeDeposit.RenovationType;
                }

                var ships = (t_smd_ShipOrderNumber._Process == storeMasterData.Process &
                    t_smd_ShipOrderNumber._Incident == storeMasterData.Incident).List<t_smd_ShipOrderNumber>(Storage.Context3);
                if (ships.Count > 0)
                {
                    var ckdList = "";
                    // ReSharper disable once LoopCanBeConvertedToQuery
                    foreach (t_smd_ShipOrderNumber ship in ships)
                    {
                        //ckdList += "<span><input type='button' class='u-btn' style='margin-right:20px' value='" + ship.Mode + "' onclick=\"downCKD('" + ship.Name + "')\" /></span>";
                        ckdList += ship.Mode + "出库单： <a class='u-btn'  style='margin-right:20px' onclick=\"downCKD('" + ship.Name + "')\" />下载</a>";
                    }
                    td_ckdList.InnerHtml = ckdList;
                }
                else
                {
                    td_ckdList.InnerHtml = "没有生成过的出库单。";
                }

                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;
                btn_print.Visible = true;

                return true;
            }

            return false;
        }
        #endregion

        #region 获取固定资产号
        private string GetFullSet(string deliveryType)
        {
            var type = deliveryType == "STD" ? "RT" : deliveryType == "DIR" ? "DRT" : "TT";
            var fullset = type + DateTime.Now.Year;

            var device = (t_smd_Device._DeliveryType == deliveryType & t_smd_Device._FullSetSN.Like("%" + fullset + "%")).ListFirst<t_smd_Device>(Storage.Context3, "FullSetSN desc");

            var strNumber = "";

            if (device != null)
            {
                var number = Utils.StrToInt(device.FullSetSN.Split('-')[1].Trim(), 0);
                number += 1;
                if (number >= 0 && number < 10)
                {
                    strNumber = "00" + number;
                }
                else if (number >= 10 && number < 100)
                {
                    strNumber = "0" + number;
                }
                else if (number >= 100)
                {
                    strNumber = number.ToString(CultureInfo.InvariantCulture);
                }
            }
            else
            {
                strNumber = "001";
            }
            return fullset + "-" + strNumber;

        }
        #endregion

        #region 更新数量
        private void UpdateInitQuantity(string name)
        {
            if (name != "")
            {
                var pc = (t_smd_InStock._Name == name).ListFirst<t_smd_InStock>(Storage.Context3);
                if (pc != null)
                {
                    pc.InitQuantity = pc.InitQuantity + 1;
                    Storage.Save(Storage.Context3, pc);
                }
            }
        }
        #endregion

        #region 发送邮件
        private void sendEmail()
        {
            DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");

            string link = ConfigurationManager.AppSettings["ToLink"];
            string Region = uc_store1.store.Region;
            string sql = string.Format("select * from AkzoNobelSMD..UserEmail where Mtype = '{0}' and MStatus = 0 and Region='{1}'", Convert.ToInt32(t_PublicEnum.MType.TemporaryEquipment).ToString(), Region.ToUpper());
            DataTable rows = DbHelperSQL.Query(sql).Tables[0]; //获得所有邮箱              
            //LogDebug(rows.Count.ToString());
            //LogDebug(rows.ToString());
            var store = (t_smd_Store._StoreID == Storeid).ListFirst<t_smd_Store>(Storage.Context3);
            TaskAPI["E_AuthID"] = store.AuthID;
            TaskAPI["E_StoreName"] = store.StoreName;
            TaskAPI["E_EapproveSN"] = store.EapproveSN;
            TaskAPI["E_StoreAddress"] = store.StoreAddress;
            TaskAPI["E_Province"] = store.Province;
            TaskAPI["E_NewFitment"] = store.NewFitment;
            TaskAPI["E_Link"] = link;
            TaskAPI["E_Time"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            var Email = string.Empty;
            if (rows.Rows.Count > 0)
            {

                foreach (DataRow item in rows.Rows)
                {
                    Email += item["Email"].ToString() + ';';
                }
            }

            TaskAPI["E_Email"] = Email.TrimEnd(';');

        }
        #endregion

        #region 流程IsFinance赋值
        /// <summary>
        /// 流程IsFinance赋值
        /// </summary>
        public int IsFinance()
        {
            //查询步骤表内 是否是跳转至第三方转移
            DbHelperSQL.connectionString = PubConstant.GetConnectionString("oleDB");
            string sqlAssessment = @"select * from t_Assessment with(nolock) where process='New Store Deposit Receive' and Step='Submit Document' AND Opinion=2 AND incident=" + TaskAPI.Incident;
            using (DataTable dt = DbHelperSQL.Query(sqlAssessment).Tables[0])
            {
                if (dt.Rows.Count > 0) { TaskAPI["IsFinance2"] = 1; return 2; }
            }

            //DbHelperSQL.connectionString = PubConstant.GetConnectionString("bpmDB");

            string sql = @"select * from t_Assessment with(nolock) where process='New Store Deposit Receive' and  incident = " + TaskAPI.Incident;

            if (TaskAPI.GetVariableBySingleValue("IsFinance") == "1")
            {
                // TaskAPI["IsFinance"] = 2;
                return 2;
            }
            else if (DwzAssessment1.Assessment.Opinion == "2" && TaskAPI.Step == "Submit Document" && TaskAPI.GetVariableBySingleValue("IsRenovation") == "1")
            {

                sql += " and step = 'Finance Margin Confirm' and Opinion = 1";

                return DbHelperSQL.Query(sql).Tables[0].Rows.Count > 0 ? 2 : 0;
            }
            else if (TaskAPI.Step == "Finance Confirm" && TaskAPI.GetVariableBySingleValue("IsRenovation") == "1" && TaskAPI.GetVariableBySingleValue("IsDevice") == "1" && TaskAPI.GetVariableBySingleValue("FinanceConfirmed") != "0")
            {
                sql += " and step = 'Finance Margin Confirm' and Opinion = 1";

                return DbHelperSQL.Query(sql).Tables[0].Rows.Count > 0 ? 2 : 0;

            }
            else if (TaskAPI.Step == "Finance Margin Confirm" && TaskAPI.GetVariableBySingleValue("IsRenovation") == "1" && TaskAPI.GetVariableBySingleValue("IsDevice") == "1" && TaskAPI.GetVariableBySingleValue("FinanceConfirmed") != "0")
            {
                //是否是第三方转移

                sql += " and step = 'Finance Confirm' and Opinion = 1";

                return DbHelperSQL.Query(sql).Tables[0].Rows.Count > 0 ? 2 : 0;
            }
            else
            {
                return 1;
            }
        }
        #endregion

        #region 发机逻辑验证
        private bool CheckInformDevice(out string returnMsg)
        {
            t_StoreMasterData storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
            returnMsg = string.Empty;
            if (storeMasterData != null && storeMasterData.ApplicationType.IndexOf("(") > 0)
            {
                string typename = storeMasterData.ApplicationType.Substring(0, storeMasterData.ApplicationType.IndexOf("("));

                string type = storeMasterData.ApplicationType.Substring(storeMasterData.ApplicationType.IndexOf("(") + 1, storeMasterData.ApplicationType.Length - storeMasterData.ApplicationType.IndexOf("(") - 2);

                string lDispen = l_DispenseModel.Text.Trim();
                string lShaker = l_ShakerModel.Text.Trim();
                string lPc = l_PcModel.Text.Trim();
                string lAmount = l_sb_Amount.Text;
                string lBuydeposit = l_BuyMachineDeposit.Text;
                bool bDispen = string.IsNullOrEmpty(lDispen);
                bool bShaker = string.IsNullOrEmpty(lShaker);
                bool bPc = string.IsNullOrEmpty(lPc);
                bool blDispen = lDispen.IndexOf("不需要") == -1;
                bool blShaker = lShaker.IndexOf("不需要") == -1;
                if (typename.IndexOf("新机") > -1)
                {
                    if (type == "STD")
                    {
                        if (!bDispen & !bShaker & !bPc)
                        {
                            if (Double.Parse(lAmount) > 0 || Double.Parse(lBuydeposit) > 0)
                            {
                                returnMsg = "保证金金额与购买设备不相符,请驳回流程重新提交";
                                return false;
                            }
                        }

                    }
                    else if (type == "DIR")
                    {

                        if (!bDispen && !bShaker && !bPc & blDispen & blShaker)
                        {
                            if (lDispen == "M3")
                            {
                                if (Double.Parse(lAmount) != 6000 || Double.Parse(lBuydeposit) != 23000)
                                {
                                    if (Double.Parse(lAmount) != 0 && Double.Parse(lBuydeposit) != 29000)
                                    {
                                        returnMsg = "保证金金额与购买设备不相符,请驳回流程重新提交";
                                        return false;
                                    }
                                }
                            }
                            else
                            {
                                if (Double.Parse(lAmount) != 6000 || Double.Parse(lBuydeposit) != 40000)
                                {
                                    if (Double.Parse(lAmount) != 0 && Double.Parse(lBuydeposit) != 46000)
                                    {
                                        returnMsg = "保证金金额与购买设备不相符,请驳回流程重新提交";
                                        return false;
                                    }
                                }
                            }
                        }
                        if (lShaker.IndexOf("不需要") != -1)
                        {
                            if (!bDispen && !bPc)
                            {
                                if (Double.Parse(lAmount) != 6000 || Double.Parse(lBuydeposit) != 25000)
                                {
                                    if (Double.Parse(lAmount) != 0 && Double.Parse(lBuydeposit) != 31000)
                                    {
                                        returnMsg = "保证金金额与购买设备不相符,请驳回流程重新提交";
                                        return false;
                                    }
                                }

                            }
                            //当调色机型号选择M3，并且不需要震荡机的时候所做的一个保证金判断
                            if ((lDispen == "M3") && !bPc)
                            {
                                if (Double.Parse(lAmount) != 6000 || Double.Parse(lBuydeposit) != 8000)
                                {
                                    if (Double.Parse(lAmount) != 0 && Double.Parse(lBuydeposit) != 14000)
                                    {
                                        returnMsg = "保证金金额与购买设备不相符,请驳回流程重新提交";
                                        return false;
                                    }
                                }

                            }
                        }
                        if (lDispen.IndexOf("不需要") != -1)
                        {
                            if (Double.Parse(lAmount) != 6000 || Double.Parse(lBuydeposit) != 15000)
                            {
                                if (Double.Parse(lAmount) != 0 && Double.Parse(lBuydeposit) != 21000)
                                {
                                    returnMsg = "保证金金额与购买设备不相符,请驳回流程重新提交";
                                    return false;
                                }
                            }
                        }
                    }
                }
                if (typename.IndexOf("旧机") > -1 && type == "DIR")
                {
                    if (!bPc && lPc.IndexOf("转让") != -1)
                    {
                        if (Double.Parse(lAmount) != 6000 || Double.Parse(lBuydeposit) > 0)
                        {
                            if (Double.Parse(lAmount) != 0 && Double.Parse(lBuydeposit) <= 0)
                            {
                                returnMsg = "保证金金额与购买设备不相符,请驳回流程重新提交";
                                return false;
                            }
                        }
                    }
                }

            }
            return true;
        }
        #endregion
    }
}